// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/exec/join_bridge.h>
#include <pollux/exec/operator.h>

namespace kumo::pollux::exec {
    class NestedLoopJoinBridge : public JoinBridge {
    public:
        void setData(std::vector<RowVectorPtr> buildVectors);

        std::optional<std::vector<RowVectorPtr> > dataOrFuture(ContinueFuture *future);

    private:
        std::optional<std::vector<RowVectorPtr> > buildVectors_;
    };

    class NestedLoopJoinBuild : public Operator {
    public:
        NestedLoopJoinBuild(
            int32_t operatorId,
            DriverCtx *driverCtx,
            std::shared_ptr<const core::NestedLoopJoinNode> joinNode);

        void addInput(RowVectorPtr input) override;

        RowVectorPtr getOutput() override {
            return nullptr;
        }

        bool needsInput() const override {
            return !noMoreInput_;
        }

        void noMoreInput() override;

        BlockingReason isBlocked(ContinueFuture *future) override;

        bool isFinished() override;

        void close() override {
            dataVectors_.clear();
            Operator::close();
        }

        std::vector<RowVectorPtr> mergeDataVectors() const;

    private:
        std::vector<RowVectorPtr> dataVectors_;

        // Future for synchronizing with other Drivers of the same pipeline. All build
        // Drivers must be completed before making data available for the probe side.
        ContinueFuture future_{ContinueFuture::makeEmpty()};
    };
} // namespace kumo::pollux::exec
